﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using MineBoxRelease.Model;
using MineBoxRelease.View;

namespace MineBoxRelease.Core.View.Creator
{
    class MusicBoxViewCreator : IViewCreator
    {
        public BaseView Create(XmlElement root)
        {
            MusicBoxView view;
            try
            {
                string tabTitle = root.GetAttribute("title");
                XmlNodeList nodes = root.GetElementsByTagName("music");
                ObservableCollection<Music> list = new ObservableCollection<Music>();
                foreach (XmlNode node in nodes)
                {
                    string path = node.Attributes["path"].InnerText;
                    Music music = MusicHelper.MusicFromFile(path);
                    list.Add(music);
                }
                view = new MusicBoxView(tabTitle);
                view.MusicList = list;
            }
            catch (Exception)
            {
                throw;
            }
            return view;
        }

        public BaseView Create(string title = null)
        {
            if (title == null || title.Equals("")) title = "音乐盒子";
            return new MusicBoxView(title);
        }

        public void Save(BaseView view, string path)
        {
            try
            {
                MusicBoxView v = view as MusicBoxView;
                ObservableCollection<Music> list = v.MusicList;
                XmlTextWriter writer = new XmlTextWriter(path, Encoding.UTF8);
                writer.Formatting = Formatting.Indented;
                writer.WriteStartDocument();
                /*根节点*/
                writer.WriteStartElement("viewxml");
                writer.WriteAttributeString("title", v.Title);
                writer.WriteAttributeString("type", "MusicBox");

                foreach (Music music in list)
                {
                    writer.WriteStartElement("music");
                    writer.WriteAttributeString("title", music.Title);
                    writer.WriteAttributeString("path", music.Path);
                    writer.WriteEndElement();
                }

                writer.WriteEndElement();
                writer.WriteEndDocument();
                writer.Close();
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
